import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import { GeofenceSettings } from '../types/Reminder';
import StorageService from './storage';
import NotificationService from './notification';

// 定义地理围栏任务名称
const GEOFENCE_TASK_NAME = 'GEOFENCE_TASK';

// 检查任务是否已注册
if (!TaskManager.isTaskDefined(GEOFENCE_TASK_NAME)) {
  TaskManager.defineTask(GEOFENCE_TASK_NAME, async ({ data, error }: any) => {
    if (error) {
      console.error('Geofence task error:', error);
      return;
    }

    if (data) {
      const { eventType, region } = data;
      console.log(`Geofence event: ${eventType} for region ${region.identifier}`);

      // 处理地理围栏事件
      if (eventType === Location.GeofencingEventType.Exit) {
        try {
          // 获取地理围栏设置
          const geofences = await StorageService.getGeofences();
          const geofence = geofences.find(g => g.id === region.identifier);

          if (geofence && geofence.isEnabled) {
            // 检查当前时间是否在设定范围内
            const now = new Date();
            const startTime = new Date(`1970-01-01T${geofence.startTime}`);
            const endTime = new Date(`1970-01-01T${geofence.endTime}`);
            const currentTime = new Date(`1970-01-01T${now.getHours()}:${now.getMinutes()}`);

            // 判断当前时间是否在 startTime 和 endTime 之间
            const isWithinTimeRange = currentTime >= startTime && currentTime <= endTime;

            if (isWithinTimeRange) {
              // 发送地理围栏提醒
              await NotificationService.scheduleReminderNotification({
                id: `geofence_${geofence.id}`,
                title: '离开公司区域提醒',
                time: now.toTimeString().slice(0, 5),
                repeat: false,
                repeatDays: [],
                advanceReminder: 0,
                reminderType: 'geofence',
                snoozeEnabled: true,
                snoozeInterval: 5,
                skipHolidays: false,
              });
            }
          }
        } catch (err) {
          console.error('Error handling geofence exit event:', err);
        }
      }
    }
  });
}

/**
 * 地理围栏服务 - 处理位置权限和地理围栏监控
 */
export const GeofenceService = {
  /**
   * 请求位置权限
   */
  async requestPermissions(): Promise<boolean> {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') {
      return false;
    }

    // 对于Android，还需要后台位置权限
    if (Platform.OS === 'android') {
      const { status: backgroundStatus } = await Location.requestBackgroundPermissionsAsync();
      return backgroundStatus === 'granted';
    }

    return true;
  },

  /**
   * 检查位置权限状态
   */
  async checkPermissions(): Promise<boolean> {
    const { status } = await Location.getForegroundPermissionsAsync();
    if (status !== 'granted') {
      return false;
    }

    if (Platform.OS === 'android') {
      const { status: backgroundStatus } = await Location.getBackgroundPermissionsAsync();
      return backgroundStatus === 'granted';
    }

    return true;
  },

  /**
   * 初始化地理围栏监控
   */
  async initializeGeofences(): Promise<boolean> {
    try {
      const hasPermissions = await this.checkPermissions();
      if (!hasPermissions) {
        console.error('Location permissions not granted');
        return false;
      }

      // 获取所有地理围栏设置
      const geofences = await StorageService.getGeofences();
      if (geofences.length === 0) {
        console.log('No geofences to monitor');
        return true;
      }

      // 转换为Expo Location需要的格式
      const regions = geofences
        .filter(g => g.isEnabled)
        .map(geofence => ({
          identifier: geofence.id,
          latitude: geofence.latitude,
          longitude: geofence.longitude,
          radius: geofence.radius,
          notifyOnEnter: false,
          notifyOnExit: true,
        }));

      if (regions.length === 0) {
        console.log('No enabled geofences to monitor');
        return true;
      }

      // 启动地理围栏监控
      await Location.startGeofencingAsync(GEOFENCE_TASK_NAME, regions);
      console.log(`Started monitoring ${regions.length} geofence(s)`);
      return true;
    } catch (error) {
      console.error('Failed to initialize geofences:', error);
      return false;
    }
  },

  /**
   * 停止地理围栏监控
   */
  async stopGeofencing(): Promise<void> {
    try {
      await Location.stopGeofencingAsync(GEOFENCE_TASK_NAME);
      console.log('Stopped geofence monitoring');
    } catch (error) {
      console.error('Failed to stop geofencing:', error);
    }
  },

  /**
   * 获取当前位置
   */
  async getCurrentLocation(): Promise<Location.LocationObject | null> {
    try {
      const hasPermissions = await this.checkPermissions();
      if (!hasPermissions) {
        return null;
      }

      return await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.Balanced,
      });
    } catch (error) {
      console.error('Failed to get current location:', error);
      return null;
    }
  },
};

export default GeofenceService;